//
//  NotificationService.m
//  NotificationService
//
//  Created by Dongxiang Xu on 2025/7/1.
//

#import "NotificationService.h"
#import <Intents/Intents.h>
#import <UIKit/UIKit.h>

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    if (self.bestAttemptContent.body.length>0) {
        self.bestAttemptContent.body = [NSString stringWithFormat:@"%@",self.bestAttemptContent.body];
    }else{
        self.bestAttemptContent.body = @"";
    }
    if (self.bestAttemptContent.subtitle.length>0) {
        self.bestAttemptContent.subtitle = [NSString stringWithFormat:@"%@", self.bestAttemptContent.subtitle];
    }else{
        self.bestAttemptContent.subtitle = @"";
    }
    if (self.bestAttemptContent.title.length>0) {
        self.bestAttemptContent.title = [NSString stringWithFormat:@"%@", self.bestAttemptContent.title];
    }else{
        self.bestAttemptContent.title = @"";
    }
    
    if (@available(iOS 15.0, *)) {
        // 发送者头像url地址
        NSString *fromAvatar = self.bestAttemptContent.userInfo[@"avatar"];
        if (fromAvatar) {
            __block INImage *avatarImage;                            
            //如果网址中出现了 中文 需要进行URL编码
            fromAvatar = [fromAvatar stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            NSURL *url = [NSURL URLWithString:fromAvatar];
            //创建请求
            NSMutableURLRequest *aRequest = [NSMutableURLRequest requestWithURL:url];
            //创建网络会话对象
            NSURLSession *session = [NSURLSession sharedSession];
            //创建数据任务  系统会自动开启一个子线程
            NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                UIImage *img = [UIImage imageWithData:data];
                NSData *aData = UIImageJPEGRepresentation(img, 0.05);
                avatarImage = [INImage imageWithImageData:aData];
                if (avatarImage) {
                    NSPersonNameComponents *nameComponents = [[NSPersonNameComponents alloc] init];
                    nameComponents.nickname =  self.bestAttemptContent.title;// 用户名
                    
                    INPerson *messageSender = [[INPerson alloc]initWithPersonHandle:[[INPersonHandle alloc] initWithValue:nil type:INPersonHandleTypeUnknown] nameComponents:nameComponents displayName:self.bestAttemptContent.title image:avatarImage contactIdentifier:nil customIdentifier:self.bestAttemptContent.title isMe:NO suggestionType:(INPersonSuggestionTypeNone)];
                    
                    INSendMessageIntent *intent = [[INSendMessageIntent alloc] initWithRecipients:@[messageSender] outgoingMessageType:(INOutgoingMessageTypeOutgoingMessageText) content:self.bestAttemptContent.body speakableGroupName:[[INSpeakableString alloc]initWithSpokenPhrase:@""] conversationIdentifier: [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]] serviceName:nil sender:messageSender attachments:nil];
                    [intent setImage:avatarImage forParameterNamed:@"speakableGroupName"];
                    
                    INInteraction *interaction = [[INInteraction alloc]initWithIntent:intent response:nil];
                    interaction.direction = INInteractionDirectionIncoming;
                    [interaction donateInteractionWithCompletion:nil];
                    
                    self.bestAttemptContent =  [[request.content contentByUpdatingWithProvider:intent error:nil] mutableCopy];
                }
                contentHandler(self.bestAttemptContent);
                
            }];
            //开始任务
            [dataTask resume];
        }
    }else{
        contentHandler(self.bestAttemptContent);
    }
}

- (UIImage *)compressImage:(UIImage *)image toSize:(CGSize)size
{
  UIGraphicsBeginImageContext(size);
  [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return scaledImage;
}


- (void)serviceExtensionTimeWillExpire
{
    self.contentHandler(self.bestAttemptContent);
}

@end
